/*
 * 上海远境文化传媒有限公司 版权所有
 */
package facade;

import play.Logger;
import play.mvc.results.BadRequest;
import play.mvc.results.Forbidden;
import play.mvc.results.NotFound;

/**
 * 用于控制 Controller 的页面流转逻辑.
 * <br/>
 * 用法:
 * <pre>
 * PageResult result = meetingProcess.saveNewMeeting();
 * result.onSuccess(()-> render()).onBack(()-> add())
 *     .on(1001, ()-> renderTemplate("/index.html"))
 *     .end();
 * </pre>
 */
public class PageResult {

    /**
     * 无处理, 或处理结束.
     */
    public static PageResult DONE = new PageResult(0);

    /**
     * 正常流程, render页面或正常redirect.
     */
    public static PageResult SUCCESS = new PageResult(1);

    /**
     * 返回前一页面.
     */
    public static PageResult BACK = new PageResult(2);

    /**
     * 禁止的操作.
     */
    public static PageResult FORBIDDEN = new PageResult(3);

    /**
     * 找不到页面.
     */
    public static PageResult NOT_FOUND = new PageResult(4);

    /**
     * 没有权限的操作.
     */
    public static PageResult NO_PERMISSION = new PageResult(5);

    private int code;

    private String message;

    /**
     * 生成页面流程方向.
     * @param code 要求大于100; 100以下系统保留.
     */
    public PageResult(int code) {
        this(code, null);
    }

    public PageResult(int code, String message) {
        this.code = code;
        this.message = message;
    }


    public PageResult withMessage(String message) {
        return new PageResult(this.code, message);
    }

    public PageResult onSuccess(Runnable runnable) {
        return on(SUCCESS.code, runnable);
    }


    public PageResult onBack(Runnable runnable) {
        return on(BACK.code, runnable);
    }

    public PageResult onNoPermission(Runnable runnable) {
        return on(NO_PERMISSION.code, runnable);
    }

    public PageResult onForbidden(Runnable runnable) {
        return on(FORBIDDEN.code, runnable);
    }

    public PageResult on(int code, Runnable runnable) {
        if (this.code == code) {
            runnable.run();
            return DONE;
        }
        return this;
    }

    public int getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }

    /**
     * 兜底处理, 可以没有.
     */
    public void end() {
        if (this.code == DONE.code) {
            return; // 前面处理过.
        }

        if (this.code == NOT_FOUND.code) {
            throw new NotFound(this.message == null ? "" : this.message);
        }

        if (this.code == NO_PERMISSION.code) {
            Logger.warn("LOG03240: 没有权限, 但应该用onNoPermission()处理掉!!!!!");
            throw new BadRequest(this.message == null ? "" : this.message);
        }

        if (this.code == FORBIDDEN.code) {
            throw new Forbidden(this.message == null ? "" : this.message);
        }
    }
}
